package com.zcw.rabbitmq.chatroomv3;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.zcw.rabbitmq.chatroomv2.ChatRoom;

import java.io.IOException;


/**
 * 消息消费者
 */
public class Subscriber {

    private Channel channel;
    private String roomName;
    private String userName;

    public Subscriber(){

    }

    public Subscriber(String roomName,String userName){
        this.roomName = roomName;
        this.userName = userName;
    }

    public void getMessage(){
        String queueName = this.userName;
        // 获取房间
        if (channel == null) {
            channel = ChatRoom.getChatRoom(this.roomName, queueName);
        }
        try {
            // 接收消息成功的回调
            DeliverCallback deliverCallback = (consumerTag, delivery) ->{
                String message = new String(delivery.getBody(),"UTF-8");
                System.out.println("用户：" + queueName + "接收到消息：" + message);
            };

            // 从群聊中接收消息
            channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
